/**
 * Created with IntelliJ IDEA.
 * User: osereda
 * Date: 30.05.13
 */
package com.google.code.bankagregator.adapter.bank.sberrus.reader.deposit;

import com.google.code.bankagregator.adapter.exception.AdapterException;
import com.google.code.bankagregator.common.SiteConnect;
import com.google.code.bankagregator.entities.Currency;
import com.google.code.bankagregator.entities.Deposit;
import com.google.code.bankagregator.entities.DepositType;
import com.google.code.bankagregator.entities.State;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.List;

/**
 * Per bank product group class
 * Return all data for products located in same "physical" source
 */
public class DepositSberSertificat extends AbstractDepositSber {

    private final String PRODUCT_TITLE = "Депозитные сберегательные сертификаты";
    private final String AMOUNT_DIVIDER = "–";

    public DepositSberSertificat(String url) {
        super(url);
    }

    @Override
    public List<Deposit> getDeposits() throws AdapterException {
        List<Deposit> deposits = new ArrayList<>();

        Document page = new SiteConnect(this.getDepositPageURL()).getPage();

        String minSumLine = page.select(MIN_AMOUNT_HTML).first().text();
        String maxSumLine = page.select(MAX_AMOUNT_HTML).first().text();
        String[][] table = getTableVertical(page.select(PRODUCT_TABLE_HTML));

        String[] minAmount = getAmount(minSumLine, AMOUNT_DIVIDER);
        String[] maxAmount = getAmount(maxSumLine, AMOUNT_DIVIDER);

        for (int x = 1; x < table.length; x++) {
            String curr = table[x][0];
            int minDeposit = getValueByCurrency(minAmount, curr);
            int maxDeposit = getValueByCurrency(maxAmount, curr);

            for (int y = 1; y < table[x].length; y++) {
                int period = Integer.valueOf(table[0][y].replaceAll("\\D+", ""));
                String rateValue = table[x][y].replaceAll("[^0-9.,]+", "");
                rateValue = rateValue.replaceAll(",", ".");
                Deposit deposit = new Deposit();
                deposit.setRefill(false);
                deposit.setType(DepositType.Deposit);
                deposit.setBank(this.getBank());
                deposit.setName(PRODUCT_TITLE);
                deposit.setCurrency(Currency.valueOf(curr));
                deposit.setMaxAmount(maxDeposit);
                deposit.setMinAmount(minDeposit);
                deposit.setDepositRate(Double.valueOf(rateValue));
                deposit.setTerm(DAYS_PER_MONTH * period);
                deposit.setUrl(this.getDepositPageURL());
                deposit.setState(State.ACTIVE);
                deposits.add(deposit);
            }
        }
        return deposits;
    }
}
